package org.shj.netty.chartper11;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil;

import java.util.Date;

public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>{
	
	private WebSocketServerHandshaker handshaker;
		
	public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception{
		if(msg instanceof FullHttpRequest){// http
			System.out.println("http request");
			handleHttpRequest(ctx, (FullHttpRequest) msg);
		}else if(msg instanceof WebSocketFrame){//Web Socket
			System.out.println("Web Socket request");
			handleWebSocketFrame(ctx, (WebSocketFrame) msg);
		}
	}
	
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception{
		System.out.println("channelReadComplete()");
		ctx.flush();
	}
	
	private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception{
		if(!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))){
			System.out.println("HTTP 解码失败，返回HTTP异常");
			sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
			return;
		}
		
		WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://localhost:8080/websocket", null, false);
		handshaker = wsFactory.newHandshaker(req);
		if(handshaker == null){
			WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
		}else{
			System.out.println("handshake()");
			handshaker.handshake(ctx.channel(), req);
		}
	}
	
	private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame){
		if(frame instanceof CloseWebSocketFrame){ //判断是否关闭链路
			System.out.println("frame is 关闭链路");
			handshaker.close(ctx.channel(), (CloseWebSocketFrame)frame.retain());
			return;
		}
		
		if(frame instanceof PingWebSocketFrame){//判断是否是ping消息
			System.out.println("frame is ping消息");
			ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
			return;
		}
		
		if(!(frame instanceof TextWebSocketFrame)){ //本例仅支持文本消息
			System.out.println("仅支持 文本消息");
			throw new UnsupportedOperationException(String.format("%s frame types not supported.", frame.getClass().getName()));
		}
		
		//返回应答消息
		String request = ((TextWebSocketFrame) frame).text();
		System.out.println(String.format("%s received %s", ctx.channel(), request));
		
		ctx.channel().write(new TextWebSocketFrame(request + ", the now time is: " + new Date()));
	}
	
	private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res){
		//返回应答给客户端
		if(res.status().code() != 200){
			System.out.println("返回200");
			ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
			res.content().writeBytes(buf);
			buf.release();
			HttpHeaderUtil.setContentLength(res, res.content().readableBytes());
		}
		
		//如果是非 keep-alive 关闭连接
		ChannelFuture f = ctx.channel().writeAndFlush(res);
		if(!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200){
			System.out.println("返回关闭连接");
			f.addListener(ChannelFutureListener.CLOSE);
		}
	}
	
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
		cause.printStackTrace();
		ctx.close();
	}
}
